package com.rfsp.common.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.rfsp.common.config.PropertyConfig;
import com.rfsp.common.mapper.PrivilegeMapper;

//@Component("authc")
public class URLPathFilter extends AccessControlFilter{

	@Autowired
	private PrivilegeMapper privilegeMapper;

	@Autowired
	PropertyConfig config;
	/**
	 *AccessControlFilter的onPreHandle方法调用了isAccessAllowed||onAccessDenied方法，所以此方法可以不用覆盖
	 */
//	@Override
//	public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
//			throws Exception {
//		
//		String requestUrl = getPathWithinApplication(request);
//		if(requestUrl.indexOf("?")>0) {
//			requestUrl = requestUrl.substring(0,requestUrl.indexOf("?"));
//		}
//		Subject subject = SecurityUtils.getSubject();
//		if(!subject.isAuthenticated()) {
//			WebUtils.issueRedirect(request, response, "/");
//			return false;
//		}
//		Set<String> userPermissionUrls = ShiroSubject.getPermissions("userPermissionUrls");
//		if(userPermissionUrls.contains(requestUrl)) {
//			return true;
//		}
//		//没有权限
//		WebUtils.issueRedirect(request, response, "/login/unauthorized");
//		return false;
//	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		String uri =  getPathWithinApplication(request);
		if(StringUtils.isNotEmpty(uri) && !"null".equals(uri)) {
			uri = uri.substring(1);
		}
		if(StringUtils.isEmpty(ShiroUtils.getUserCode())){
			return false;
		}else{
			
			boolean result = subject.isPermitted(uri);
			if(!result) {
				WebUtils.issueRedirect(request, response, "/login/unauthorized", null, true, false);
			}
			return result;
		}
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		
		//如果登录过
		if(SecurityUtils.getSubject().isAuthenticated()){
			String url =  getPathWithinApplication(request);
			request.setAttribute("url", url);
			return true;
		}else{
			String userCode = ShiroUtils.getUserCode();
			if(StringUtils.isEmpty(userCode)) {
				request.getRequestDispatcher("/login/err").forward(request, response);
            }else {
				request.getRequestDispatcher("/login/unauthorized").forward(request, response);
            }
            return false;
//			ShiroUtils.kickOutUser(ShiroUtils.getUserCode());
		}
		
	}

}
